编写简单的SpringBoot单元测试类 您所在的位置:网站首页 springboot 结果类 编写简单的SpringBoot单元测试类

编写简单的SpringBoot单元测试类

#编写简单的SpringBoot单元测试类| 来源: 网络整理| 查看: 265

目录

一、引入测试依赖

二、 Spring Boot 测试

1、注解解释:

(1)@RunWith

(2)@SpringBootTest

二、Spring MVC 测试

简单总结下SpringBoot开发中常用到的两个单元测试方法:

(1) Spring Boot 测试

(2) Spring MVC 测试

一、引入测试依赖

首先引入SpringBoot测试的依赖

org.springframework.boot spring-boot-starter-test test

依赖 spring-boot-starter-test 测试模块,其中包括JUnit、Hamcrest、Mockito

在spring-boot中,模块的依赖都是以starter的方式进行,以 spring-boot-starter-方式命名,指明了具体的模块。spring-boot生态中提供了丰富的starter供开发者使用。

Spring Boot的启动器Starter

二、 Spring Boot 测试

SpringBoot的单元测试非常简单,只要在测试类上,添加@RunWith和@SpringBootTest注解就可以了。

示例代码如下(注:此代码不能直接执行,只做结构展示):

1、注解解释: (1)@RunWith

 是一个测试运行器,JUnit所有的测试方法都有测试运行器负责执行。

JUnit为单元测试提供了一个默认的测试运行器BlockJUnit4Runner,但是没有限制必须使用默认的运行器。

SpringRunner是SpringJUnit4ClassRunner(BlockJUnit4Runner的拓展)的别名。像这样,@RunWith(JUnit4.Class)就是指定用JUnit4来运行。

(2)@SpringBootTest

它可以用作标准spring-test

@ContextConfiguration注释的替代方法。注解的工作原理是通过SpringApplication在测试中创建ApplicationContext。

所以Spring1.4以上的版本一般情况下是这样的:

@RunWith(SpringRunner.class) @SpringBootTest public class SpringbootStarterTests { }

在普通Spring项目中的测试一般情况下是这样的:

@RunWith(SpringRunner.class) @ContextConfiguration(locations={"classpath:spring-servlet.xml", "classpath:spring-dao-test.xml", "classpath:spring-service-test.xml"}) public class MemberTest { }

@BeforeClass:针对所有测试,只执行一次,且必须为static void

​​​​​​@Before  :执行测试方法前执行

@After  :执行测试方法后执行

@Test :测试方法

@AfterClass:针对所有测试,只执行一次,且必须为static void

一个单元测试类的执行顺序为:

@BeforeClass -> @Before -> @Test -> @After -> @AfterClass

每一个测试方法的调用顺序为:

@Before -> @Test -> @After

二、Spring MVC 测试

测试Controller接口,需添加注解@WebAppConfiguration

@RunWith(SpringRunner.class) @SpringBootTest @WebAppConfiguration public class UserServiceImplTest { @Autowired private UserService userService; @Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc; @Before public void before(){ // 指定WebApplicationContext,将会从该上下文获取相应的控制器并得到相应的MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); LogUtils.info("单元测试开始执行..."); } @Test public void selectUser() throws Exception { mockMvc.perform( post("http://localhost:8080/demo/User/getUser") .contentType(MediaType.APPLICATION_JSON_UTF8) // 传参格式 .content("{\"name\":\"xiaohong\"}") // JSON 格式传参 ) .andExpect(status().isOk()) // 添加断言 .andDo(MockMvcResultHandlers.print()) // 打印操作 .andReturn(); } @After public void after(){ LogUtils.info("单元测试执行结束..."); } }

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有